<template>
  <div style="margin-bottom: 100px;">
    <div style="margin: 20px 0; font-size: 20px; color: #1E90FF">Exam List</div>
    <div v-for="item in tableData" :key="item.id"
         style="border: 1px solid #ccc; padding: 10px; border-radius: 10px; margin: 10px 0">
      <div style="color: #333; margin: 10px 0; font-size: 20px">{{ item.name }}</div>
      <div style="color: #666; margin: 10px 0;">
        <span>Classroom: {{ item.room }}</span>
        <span style="margin-left: 20px">Time: {{ item.time }}</span>
        <span style="margin-left: 20px">Invigilator: {{ item.teacher }}</span>
        <span style="margin-left: 20px">Exam status: {{ item.state }}</span>
      </div>
      <div style="margin: 10px 0">
        <el-button type="primary" v-if="item.state === 'has not started'" @click="sign(item.id)">Sign up</el-button>
        <el-button v-if="item.enable && item.state === 'in progress'" style="margin-left: 20px" type="primary"
                   @click="doPaper(item.id)">Start Exam
        </el-button>
      </div>
    </div>

    <el-dialog
        :show-close="false"
        :visible.sync="dialogVisible"
        title="Face Verification"
        width="290px">
      <!--Video Display-->
      <video
          v-show="!isPhoto"
          ref="video"
          autoplay
          class="mt20"
          height="188"
          style="background: #d9d9d9"
          width="250"
      ></video>
      <!--Canvas to capture the stream-->
      <canvas v-show="isPhoto" ref="canvas" height="188" style="background-color: #eaeaea" width="250"></canvas>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">Cancel</el-button>
        <el-button type="primary" @click="verify">Verify</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "FrontHome",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      name: "",
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},

      dialogVisible: false,
      isPhoto: false,
      examId: null,
    }
  },
  created() {
    this.load()
  },
  methods: {
    doPaper(examId) {
      this.dialogVisible = true
      this.callCamera()
      this.examId = examId
      //this.$router.push('/front/paper?examId=' + examId)
    },
    sign(examId) {
      let form = {userId: this.user.id, examId: examId}
      this.request.post("/sign", form).then(res => {
        if (res.code === '200') {
          this.$message.success("Registration succeeded")
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    load() {
      this.request.get("/exam/page/front", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
      this.request.get("/course").then(res => {
        this.courses = res.data
      })
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },

    // Close face verification dialog
    closeDialog() {
      this.dialogVisible = false
      this.closeCamera()
      this.isPhoto = false
    },
    // Submit face verification, and enter the exam page if the verification passes
    verify() {
      this.photograph()
      this.commit()
    },

    // Call the camera
    callCamera() {
      console.log(this.isCamera);
      // Invoke the computer camera API in H5
      navigator.mediaDevices
        .getUserMedia({
          audio: true, // Turn on audio
          video: true, // Turn on video
        })
        .then((success) => {
          var videoTracks = success.getVideoTracks();
          this.$refs["video"].srcObject = success;
          this.isCameraFlag = false;
          // Real-time camera effect
          this.$refs["video"].play();
        })
        .catch((error) => {
          console.error("Failed to turn on the camera. Please check if the camera is available!");
        });
    },

    // Take a photo
    photograph() {
      this.isPhoto = true
      let ctx = this.$refs["canvas"].getContext("2d");
      ctx.drawImage(this.$refs["video"], 0, 0, 250, 188);
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
      let str = imgBase64.replace("data:image/jpeg;base64,", "");
      this.base64 = str;

      this.closeCamera()
    },

    // Close the camera
    closeCamera() {
      if (!this.$refs["video"].srcObject) return;
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
    },

    // Submit for face verification
    commit() {
      // Get the canvas object
      let canvas = this.$refs["canvas"]
      var formData = new FormData();
      var base64File = canvas.toDataURL("image/jpeg", 0.7);
      //var userName = $("#userName").val();
      formData.append("file", base64File);
      formData.append("name", this.user.username);
      formData.append("groupId", "101");
      $.ajax({
        type: "post",
        url: "http://localhost:8089/faceSearch",
        data: formData,
        contentType: false,
        processData: false,
        async: false,
        success: (text) => {
          var res = JSON.stringify(text)
          if (text.code == 0 && this.user.username == text.data.name) {
            this.$message({
              message: 'Face verification succeeded, entering exam',
              type: 'success'
            });
            this.$router.push('/front/paper?examId=' + this.examId)
          } else {
            this.$message.error('Face does not match or is not registered, verification failed');
          }
        },
        error: function (error) {
          alert(JSON.stringify(error))
        }
      });
    }
  }
}
</script>

<style>

</style>
